<template>
  <div class="hello">
    <!--<h1>{{ msg }}</h1>-->
    <!--<h2>Essential Links</h2>-->
    <div class="content">
      <div id="poster">
        <canvas v-show="false" id="gameCanvas"></canvas>
        <img id="gameimg" />
      </div>
    </div>
    <!--底部日期显示-->
    <div class="footview">
      <div class="timeview">
        <p class="timeviewf">{{ nowDay }}</p><p class="timeviewd">{{ weekDay }}<br>{{ yearDay }}</p>
      </div>
      <el-button class="changeBtn" v-on:click="changeBtnClick" round>换一个</el-button>
      <!--<div class="moodview">-->
        <!--<router-link to="/driver">-->
          <!--<img src="../assets/png/taiyang.png"/>-->
        <!--</router-link>-->

        <!--<img src="../assets/png/nanguo.png"/>-->
        <!--<img src="../assets/png/biji.png"/>-->
      <!--</div>-->
    </div>
  </div>
</template>

<script>//var chineseLunar = require("chinese-lunar");
import LunarCalendar from "lunar-calendar"
import { getApplinziCalendar, upload } from '../../api/httpApi'


export default {
  name: 'index',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App',
      yearDay: '',
      weekDay: '',
      nowDay: '',
    }
  },
  created() {

  },
  mounted: function () {
    this.init()
  },
  methods: {
    init() {
      this.getData()
    },
    changeBtnClick(){
      console.log("changeBtnClick");
      var data = {
        new:1
      };
      this.getData(data)
    },
    async getData(data) {
      const calendar = await getApplinziCalendar(data);
      console.log(calendar);
      if (calendar.data.code === 0) {
        // var sreger = new RegExp("市|省|自治区|区","igm");
        // var city = ipAdd.data.province.replace(sreger,'')
        // const weather = await getAxiosWeather({name:'上海'})
        // console.log(weather.data)
        if (calendar.data.code === 0) {

          var calendarData = calendar.data.data;
          // calendarData.date = '2018-06-02';
          var yd = this.getYearDay(calendarData.date);
          this.yearDay = yd;
          var wd = this.getWeekDay(calendarData.date);
          this.weekDay = wd;
          var nd = this.getNowDay(calendarData.date);
          this.nowDay = nd;

          var canvas = document.getElementById("gameCanvas");
          var ctx = canvas.getContext("2d");

          var level = 2.5;
          canvas.width= 300 * level//this.getDomWidth("poster");
          canvas.height= 482 * level//this.getDomHeight("poster");
          ctx.lineJoin = "round";
          ctx.fillStyle="#FFF";
          ctx.fillRect(2, 2,  canvas.width-4, canvas.height-4);
          ctx.lineWidth = 4;
          ctx.strokeRect(2, 2,  canvas.width-4, canvas.height-4);
          ctx.lineWidth = 2;
          canvasLine(ctx,0,15,canvas.width,15)

          ctx.lineWidth = 2;
          canvasLine(ctx,0,canvas.height/3*2,canvas.width,canvas.height/3*2)

          ctx.lineWidth = 2;
          canvasLine(ctx,canvas.width/4,15,canvas.width/4,canvas.height/3*2)


          ctx.fillStyle = "#333";
          ctx.font = "360px 'Times'";
          ctx.textAlign = "center";
          ctx.fillText(nd,canvas.width/8*5,canvas.height/3*1.25);
          ctx.font = "32px '黑体'";
          ctx.fillStyle = "#222";
          ctx.fillText(calendar.data.data.keyword,canvas.width/8*5,canvas.height/3*1.75);

          ctx.textAlign = 'center';
          ctx.textBaseline = 'top';
          ctx.font = "32px '黑体'";
          var fontWidth = (canvas.width/4-50)
          var lunarSting = this.getLunarString(calendarData.date)
          canvasTextAutoVerticalLine(lunarSting,canvas,30,fontWidth,fontWidth/2)
          var solarString = this.getSolarString(calendarData.date)
          canvasTextAutoVerticalLine(solarString,canvas,30,fontWidth-fontWidth/2,fontWidth/2)

          ctx.textAlign = "left";
          var dataString = calendar.data.data.content

          canvasTextAutoHorizontalLine(dataString,canvas,50,canvas.height/3*2+80,60);
          canvasTextMaekHorizontalLine("--小布日历",canvas,520,canvas.height/3*2+280,60);


          var img = canvas.toDataURL("image/png");
          var gameimg = document.getElementById("gameimg");
          //gameimg.src= img
          canvasDataURL(img, {
            quality: 1.0
          }, function(base64Codes){
            let blob = base64ToBlob(base64Codes);
            console.log(blob);
            var data = new FormData();
            data.append("file",base64Codes);
            upload(data).then((res)=>{
              var rt = res.data;
              console.log(rt);
            });
            gameimg.src= base64Codes;
          });


          // var imgObj = new Image();
          // imgObj.setAttribute("crossOrigin",'Anonymous')
          // imgObj.src="https://csdnimg.cn/pubfooter/images/csdn_cs_qr.png";
          // //待图片加载完后，将其显示在canvas上
          // imgObj.onload = function(){
          //   ctx.drawImage(this, canvas.width-124, canvas.height-124,120,120);
          //   var img = canvas.toDataURL("image/png", 0.1);
          //   var gameimg = document.getElementById("gameimg");
          //   gameimg.src= img
          //   var imgFile = base64ToBlob(gameimg.src)
          //   console.log(imgFile)
          //
          //   canvasDataURL(gameimg.src, {
          //     quality: 0.1
          //   }, function(base64Codes){
          //     console.log(base64ToBlob(base64Codes))
          //     gameimg.src= base64Codes
          //   });
          // }

        }
      }
    },
    //获取年月
    getYearDay:function(date){
      var d = date ? new Date(date):new Date();
      var curr_date = d.getDate();
      var curr_month = d.getMonth() + 1;
      var curr_year = d.getFullYear();
      console.log(curr_month);
      String(curr_month).length < 2 ? (curr_month = "0" + curr_month): curr_month;
      String(curr_date).length < 2 ? (curr_date = "0" + curr_date): curr_date;
      var yyyyMM= curr_year + "年" + curr_month + "月";
      return yyyyMM;
    },
    //获取星期
    getWeekDay:function(date){
      var weekDay = ["星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
      var myDate = date ? new Date(date):new Date();
      return (weekDay[myDate.getDay()]);
    },
    //获取日期data
    getNowDay:function(date){
      var myDate = date ? new Date(date):new Date();
      console.log(myDate.getDate())
      return (myDate.getDate());
    },
    //获取农历日期
    getLunarString:function (date) {
      var solarDate = date ? new Date(date):new Date(); //公历2014年2月1日
      var lunar = LunarCalendar.solarToLunar(solarDate.getFullYear(),solarDate.getMonth()+1,solarDate.getDate());
      console.log(lunar)
      var space = ' '
      var fmt = lunar.lunarMonthName+
        lunar.lunarDayName+space+
        lunar.GanZhiYear+'年'+space+
        '● '+lunar.zodiac+'年'+space+
        lunar.GanZhiMonth+'月'+space+
        lunar.GanZhiDay+'日';

      return fmt
    },
    //获取公历日期
    getSolarString:function (date) {
      var solarDate = date ? new Date(date):new Date(); //公历2014年2月1日
      var space = ' '
      var fmt =
        solarDate.getFullYear()+'/'+
        (solarDate.getMonth()+1)+'/'+
        solarDate.getDate()+space+this.getWeekDay(date)
      return fmt
    }

  }
}


function canvasDataURL(path, obj, callback){
  var img = new Image();
  img.src = path;
  img.onload = function(){
    var that = this;
    // 默认按比例压缩
    var w = that.width,
      h = that.height,
      scale = w / h;
    w = obj.width || w;
    h = obj.height || (w / scale);
    var quality = 0.7;  // 默认图片质量为0.7
    //生成canvas
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');
    // 创建属性节点
    var anw = document.createAttribute("width");
    anw.nodeValue = w;
    var anh = document.createAttribute("height");
    anh.nodeValue = h;
    canvas.setAttributeNode(anw);
    canvas.setAttributeNode(anh);
    ctx.drawImage(that, 0, 0, w, h);
    // 图像质量
    if(obj.quality && obj.quality <= 1 && obj.quality > 0){
      quality = obj.quality;
    }
    // quality值越小，所绘制出的图像越模糊
    var base64 = canvas.toDataURL('image/jpeg', quality);
    // 回调函数返回base64的值
    callback(base64);
  }
}

function base64ToBlob(urlData) {
  var arr = urlData.split(',');
  var mime = arr[0].match(/:(.*?);/)[1] || 'image/png';
  // 去掉url的头，并转化为byte
  var bytes = window.atob(arr[1]);
  // 处理异常,将ascii码小于0的转换为大于0
  var ab = new ArrayBuffer(bytes.length);
  // 生成视图（直接针对内存）：8位无符号整数，长度1个字节
  var ia = new Uint8Array(ab);

  for (var i = 0; i < bytes.length; i++) {
    ia[i] = bytes.charCodeAt(i);
  }

  return new Blob([ab], {
    type: mime
  });
}

/**
 * 基本划线
 */
function canvasLine(ctx,x1,y1,x2,y2) {
  ctx.beginPath();
  ctx.moveTo(x1, y1);
  ctx.lineTo(x2, y2);
  ctx.closePath();
  ctx.stroke();
}


/**
 * 手动横排换行
 */
function canvasTextMaekHorizontalLine(str,canvas,initX,initY,lineHeight) {
  var ctx = canvas.getContext("2d");
  var lines = str.split('\n');
  for (var i = 0; i<lines.length; i++)
    ctx.fillText(lines[i], initX, initY + (i*lineHeight) );
}

/**
 * 自动横排换行
 * @param str
 * @param canvas
 * @param initX
 * @param initY
 * @param lineHeight
 */
function canvasTextAutoHorizontalLine(str,canvas,initX,initY,lineHeight){
  var ctx = canvas.getContext("2d");
  var lineWidth = 0;
  var canvasWidth = canvas.width-initX-8;
  var lastSubStrIndex= 0;
  // console.log(str);
  for(let i=0;i<str.length;i++){
    lineWidth+=ctx.measureText(str[i]).width;
    if(lineWidth>canvasWidth-initX){
      ctx.fillText(str.substring(lastSubStrIndex,i),initX,initY);
      initY +=lineHeight;
      lineWidth=0;
      lastSubStrIndex=i;
    }
    if(i==str.length-1){
      ctx.fillText(str.substring(lastSubStrIndex,i+1),initX,initY);
    }
  }
}

/**
 * 自动竖版换行
 * @param str
 * @param canvas
 * @param initX
 * @param initY
 * @param lineHeight
 */
function canvasTextAutoVerticalLine(str,canvas,initX,initY,lineHeight){
  var ctx = canvas.getContext("2d");
  var lineWidth = 0;
  var canvasWidth = canvas.height/3*2 - 18;
  var lastSubStrIndex= 0;
  for(let i=0;i<str.length;i++){
    lineWidth+=ctx.measureText(str[i]).width;
    if(lineWidth>canvasWidth-initX){
      //ctx.fillText(str.substring(lastSubStrIndex,i),initX,initY);
      ctx.fillTextVertical(str.substring(lastSubStrIndex,i), initY, initX);
      //initY +=lineHeight;
      initY -=lineHeight;
      lineWidth=0;
      lastSubStrIndex=i;
    }
    if(i==str.length-1){
      //ctx.fillText(str.substring(lastSubStrIndex,i+1),initX,initY);
      ctx.fillTextVertical(str.substring(lastSubStrIndex,i+1), initY, initX);
    }
  }
}

CanvasRenderingContext2D.prototype.fillTextVertical = function (text, x, y) {
  var context = this;
  var canvas = context.canvas;

  var arrText = text.split('');
  var arrWidth = arrText.map(function (letter) {
    return context.measureText(letter).width;
  });

  var align = context.textAlign;
  var baseline = context.textBaseline;

  if (align == 'left') {
    x = x + Math.max.apply(null, arrWidth) / 2;
  } else if (align == 'right') {
    x = x - Math.max.apply(null, arrWidth) / 2;
  }
  if (baseline == 'bottom' || baseline == 'alphabetic' || baseline == 'ideographic') {
    y = y - arrWidth[0] / 2;
  } else if (baseline == 'top' || baseline == 'hanging') {
    y = y + arrWidth[0] / 2;
  }

  context.textAlign = 'center';
  context.textBaseline = 'middle';

  // 开始逐字绘制
  arrText.forEach(function (letter, index) {
    // 确定下一个字符的纵坐标位置
    var letterWidth = arrWidth[index];
    // 是否需要旋转判断
    var code = letter.charCodeAt(0);
    if (code <= 256) {
      context.translate(x, y);
      // 英文字符，旋转90°
      context.rotate(90 * Math.PI / 180);
      context.translate(-x, -y);
    } else if (index > 0 && text.charCodeAt(index - 1) < 256) {
      // y修正
      y = y + arrWidth[index - 1] / 2 ;
    }
    context.fillText(letter, x, y);
    // 旋转坐标系还原成初始态
    context.setTransform(1, 0, 0, 1, 0, 0);
    // 确定下一个字符的纵坐标位置
    var letterWidth = arrWidth[index];
    y = y + letterWidth;
  });
  // 水平垂直对齐方式还原
  context.textAlign = align;
  context.textBaseline = baseline;
};

</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  h1, h2 {
    font-weight: normal;
  }

  ul {
    list-style-type: none;
    padding: 0;
  }

  li {
    display: inline-block;
    margin: 0 10px;
  }CSS3 border-radius

   a {
     color: #42b983;
   }

  .footview {
    position: absolute;
    width: 80%;
    height: 64px;
    background-color: #FEFFFF;
    top: 10px;
    -moz-box-shadow:0px 0px 10px #DDDDDD;
    -webkit-box-shadow:0px 0px 10px #DDDDDD;
    box-shadow:0px 0px 10px #DDDDDD;
  }

  .timeview {
    position: absolute;
    width: 170px;
    height: 34px;
    top: 0px;
  }

  .timeview p{
    display: inline-block;
  }
  .timeviewf{
    font-size: 36px;
    margin-left: 20px;
    margin-right: 10px;
    color:#515151;
  }
  .timeviewd{
    font-size: 10px;
    line-height:15px;
    color:#8a8a8a;
  }

  .moodview {
    position: absolute;
    width: 100px;
    height: 34px;
    bottom: 0px;
    right: 0px;
  }

  .moodview img{
    width: 16px;
    height: 16px;
    margin: 0 6px;
    margin-top: 5px;
  }

  .moodview p{
    width: 160px;
    height: 16px;
  }

  .changeBtn{
    float: right;
    margin-top: 10px;
    margin-right: 10px;
  }

  .content{
    position: absolute;
    bottom: 64px;
    right: 0px;
    left: 100px;
    top: 350px;
  }

  #poster {
    text-align: center;
    background-color: #fff;
    width: 300px;
    height: 482px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
    -moz-box-shadow:0px 0px 10px #E6E6E6; -webkit-box-shadow:0px 0px 10px #E6E6E6; box-shadow:0px 0px 10px #E6E6E6;
  }

  #gameimg {
    text-align: center;
    background-color: #fff;
    width: 300px;
    height: 482px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
    -moz-box-shadow:0px 0px 10px #E6E6E6; -webkit-box-shadow:0px 0px 10px #E6E6E6; box-shadow:0px 0px 10px #E6E6E6;
  }
</style>
